<template>
	<div class="upload">
		<div class="upload__content" @drop.prevent="onDragleave" @dragover.prevent="onDragover" @dragleave.prevent="onDragleave">
		<el-upload
		v-if="!$attrs.list&&!$attrs.progress||$attrs.list&&$attrs.list.length===0&&$attrs.progress&&$attrs.progress.length===0||isDrop"
		class="upload--window"
		drag
		ref="upload1"
		v-bind="$attrs"
		action=""
		:accept="acceptUploadStr"
		:on-error="uploadError"
		:disabled="disabled"
		:on-success="handleSuccess"
		:before-upload="beforeUpload"
		:show-file-list="false"
		:on-progress="onFileProgress"
		:http-request="uploadRequest">
			<div class="upload--button" :class="[disabled?'disabled-btn':'']">
				粘贴（Command V）或拖拽至此上传
			</div>
		</el-upload>
		<uploadList @userOnDrag='onUserDrag' v-else @remove="remove" v-bind="$attrs" v-on="$listeners" class="uploadList" :isHiddenDelBtn="disabled"></uploadList>
		</div>
		<el-upload action="" :accept="acceptUploadStr" ref="upload" :on-error="uploadError" :http-request="uploadRequest" v-bind="$attrs" :disabled="disabled" :on-success="handleSuccess" :before-upload="beforeUpload" :show-file-list="false" :on-progress="onFileProgress" multiple>
			<div class="upload--text" style="display: table;" :class="[disabled?'disabled-btn':'',isBorder?'isBorder':'']">
				上传本地文件
			</div>
		</el-upload>
		<!-- <el-progress
        v-if="isShowProgress"
        :text-inside="true"
        :stroke-width="24"
        :percentage="progress"
        status="success"
      ></el-progress> -->
	</div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import uploadList from './uploadList.vue';
import { uploadQiniu } from '@/utils/upload'
import Axios from 'axios'
const imageService = Axios.create({
  baseURL: '',
  responseType: 'blob'
})
@Component({
  name: 'uploader',
  components: {
    uploadList
  }
})
export default class Uplodaer extends Vue {
  @Prop({ default: false }) public disabled!: boolean;
  @Prop({ default: {} }) public item!: any;
  @Prop({ default: true }) public isBorder!: boolean; // 是否展示border
  @Prop({ default: 50 }) public fileSize!: number;
  private progress: any = 0 // 上传进度
  private isCanUpload = true
  private isShowProgress: boolean = false // 是否显示上传文件进度条
  public fileList: any[] = [];
  private acceptUploadArr = [] as any
  private fileName = ''
  private $message: any;
  private isChildMove = false; // 检测是否是子元素拖动
  private isDrop = false;
  private uploadType = Object.freeze({
    1: ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.psd', '.tif', '.jfif'],
    2: ['.mkv', '.mp4', '.avi', '.swf', '.wmv', '.rmvb', '.mov', '.mpg'],
    3: ['.txt', '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.cvs', '.xml', '.ppt', '.pptx', '.wps', '.htm', '.html', '.rtf', '.hlp'],
    4: ['.mp3', '.flac', '.ape', '.wma', '.wav', '.aac', '.m4a', '.au', '.ram', '.mmf', '.aif']
  })

  @Watch('item.attachFormat', { immediate: true })
  private attachFormatChange (newValue) {
    this.acceptUploadArr = []
    newValue.forEach(element => {
      this.acceptUploadArr = [...this.acceptUploadArr, ...this.uploadType[element]]
    });
  }

  private get acceptUploadStr () {
    return this.acceptUploadArr.length ? this.acceptUploadArr.join(',') : ''
  }

  // 拖拽移出监听
  private onDragleave (event) {
    this.isDrop = false;
  }

  // 拖拽移动监听
  private onDrop (event) {
    this.isDrop = false;
  }

  private onDragover (event) {
    if (this.isChildMove) {
      return;
    }
    this.isDrop = true;
  }

  // 子元素抛出事件
  private onUserDrag (bol) {
    this.isChildMove = bol;
  }

  private uploadError () { // 上传失败
    this.$message({ message: '文件上传失败，请重新选择文件上传', type: 'error' })
  }

  // 七牛上传
  public uploadRequest (request: any) {
    if (!this.isCanUpload) {
      return false
    }
    this.isShowProgress = true
    uploadQiniu({ type: 'crm', fileName: this.fileName }, request)
  }

  private remove (item) {
    this.fileList = this.fileList.filter((file) => file.url !== item.url)
    this.$emit('remove', item);
  }

  public onFileProgress ({ percent }, file, fileList) {
    this.$emit('progress', this.processList(fileList));
  }

  // 上传之前校验
  public async beforeUpload (file) {
    this.isCanUpload = true
    this.fileName = file.name.replace(/\s/g, '')
    if (this.disabled) {
      this.isCanUpload = false
      this.$message.error('禁止上传');
      return false;
    }
    if (!this.item.maxCount || !this.item.singleMaxMb || !this.item.attachFormat.length) {
      this.$message.error('请填写附件大小、最大个数以及附件类型');
      this.isCanUpload = false
      return false;
    }
    if (this.fileList.length >= this.item.maxCount) {
      this.isCanUpload = false
      this.$message({ message: `最多只允许上传${this.item.maxCount}个附件`, type: 'error' })
      return false
    }
    if (file.size > this.item.singleMaxMb * 1024 * 1024) {
      this.isCanUpload = false
      this.$message.error(`附件大于${this.item.singleMaxMb}mb`);
      return false;
    }
    return true
  }

  // 文件上传成功
  public handleSuccess (response, file, fileList) {
    const uploadFile = {
      url: response.domain + '/' + response.key,
      fileName: file.name
    };
    this.fileList.push(uploadFile);
    this.$emit('uploadSuccess', uploadFile);
    this.$emit('progress', this.processList(fileList));
  }

  private processList (list) {
    console.log(list);
    return list.filter((item) => {
      return item.status !== 'ready' && item.percentage < 100;
    }).map(({ name, percentage }) => {
      return { name, percentage: Math.floor(percentage) };
    });
  }
}
</script>

<style lang="stylus" scoped>
.upload {
	.header {
		padding 16px
		font-size 16px
		font-weight 500
		border-bottom 1px solid rgba(0, 0, 0, 0.05)
	}
	.upload__content {
		position relative
		// overflow auto
		.upload--window {
			height 100%
			// padding 8px 0
			/deep/ .el-upload-dragger {
				height 100%
			}
		}
	}
	/deep/ .el-upload {
		width: 100%
		.upload--button {
			width 100%
			height 100%
			line-height 90px
			background rgba(0, 0, 0, 0.03)
			border 1px dashed rgba(0, 0, 0, 0.1)
			box-sizing border-box
			color #000000
			opacity 0.6
			font-size 14px
		}
		.upload--text {
			font-size 14px
			text-align left
			color #1E63F5
			position relative
			.iconPlus {
				color #1E63F5
				vertical-align bottom
			}
		}
		.isBorder {
			border 0 !important
			text-align right
			padding 0
			font-size 14px
			line-height 20px
		}
		.disabled-btn {
			&:hover {
				cursor not-allowed
			}
		}
		.el-upload-dragger {
			width 100%
			border 0
			height 90px
			&.is-dragover {
				background-color rgba(30, 99, 245, 0.1)
				.upload--button {
					color #1E63F5
					border 1px dashed #1E63F5
					opacity 1
				}
			}
		}
	}
}
</style>
